/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.node;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.StringTokenizer;

import cgl.narada.protocol.GatewayInfo;
import cgl.narada.protocol.NodeAddress;
import cgl.narada.protocol.ProtocolHandler;
import cgl.narada.transport.TransportException;

/**
 * ServerNode.java
 * 
 * @author Shrideep Pallickara $Revision$ $Date$
 */

public class ServerNode implements NodeDebugFlags {
    /** The nodeAddress for this specific Server Node */
    private NodeAddress thisNodeAddress;

    /**
     * Specifies the number of links allowed at each level. A 0 at level-i
     * indicates that this node can never be a level-i gateway
     */
    private short[] connectionVector = { 5, 4, 3, 0, 0 };

    /**
     * Use by the NodeAdditonProtocol to decide if a node should be allowed to
     * be part of its unit/super-unit.
     */
    private String ipDiscriminator;

    /** The number of levels used by the system */
    private short systemLevels;

    /** The protocol Handler */
    private ProtocolHandler protocolHandler;

    /**
     * Gateway Info : Maintains information about revelant gatekeepers within
     * the system
     */
    private GatewayInfo gatewayInfo;

    private String moduleName = "ServerNode: ";

    public ServerNode(boolean assignedAddress) {
        systemLevels = 3;
        int[] address = new int[systemLevels + 1];
        ipDiscriminator = "128.230";
        int addressId;
        /** An address of 0.0.0.0 indicates that this node needs an address */
        if (assignedAddress)
            addressId = 1;
        else
            addressId = 0;

        for (int i = 0; i < systemLevels + 1; i++)
            address[i] = addressId;
        gatewayInfo = new GatewayInfo(systemLevels);

        thisNodeAddress = new NodeAddress(address);

        protocolHandler = new ProtocolHandler(thisNodeAddress,
                                              connectionVector,
                                              5000 /* concurrentConnLimit */,
                                              ipDiscriminator, gatewayInfo);
        protocolHandler.initializeProtocolSuite();
        protocolHandler.unsetForwardingService();
        if (assignedAddress) {
            protocolHandler.setAssignedAddress(thisNodeAddress);
        }

        protocolHandler.start();
        gatewayInfo.setProtocolHandler(protocolHandler);
        if (ServerNode_Debug) {
            System.out.println(moduleName + "This server node initialized with"
                + "\n" + "     NodeAddress = " + thisNodeAddress + "\n"
                + "     connectionVector = " + connectionVector + "\n"
                + "     ipDiscriminator = " + ipDiscriminator);
        }

    }

    public NodeAddress getNodeAddress(boolean checkForValid) {
        thisNodeAddress = protocolHandler.getAssignedAddress();
        if (!checkForValid) {
            return thisNodeAddress;
        }
        // System.out.println(moduleName + thisNodeAddress);

        int[] addressInInts = thisNodeAddress.getAddressInInts();
        for (int i = 0; i < addressInInts.length; i++) {
            if (addressInInts[i] == 0) {
                return null;
            }
        }
        return thisNodeAddress;
    }

    public void setUpNode(Properties props, String transportType) {
        try {
            protocolHandler.loadCommunicationsOfType(props, transportType);
        } catch (TransportException transEx) {
            System.out.println(transEx);
        }
    }

    public void nodeAdditionRequest(String node, int level) {
        int[] levels = { 0, level };
        byte[] request = protocolHandler.constructNodeAdditionRequest(levels,
                                                                      true);
        if (request == null) {
            return;
        }
        protocolHandler.sendTo(node, request);
    }

    public void gatewayCreationRequest(String node, int gatewayLevel) {
        byte[] request = protocolHandler
            .constructGatewaySetupRequest(node, gatewayLevel);
        if (request == null)
            return;
        protocolHandler.sendTo(node, request);
    }

    public void connectTo(String hostName, int portNum, String transport) {
        Properties props = new Properties();
        props.put("hostname", hostName);
        props.put("portnum", Integer.toString(portNum));
        try {
            String linkId = protocolHandler.setupLink(props, transport);
            System.out.println(linkId);
        } catch (TransportException transEx) {
            System.out.println(transEx);
        }
    }

    public String createLink(Properties props, String transportType) {
        try {
            return protocolHandler.setupLink(props, transportType);
        } catch (TransportException transEx) {
            System.out.println(transEx);
        }
        return null;
    }

    public void sendTo(String client, byte[] data) {
        protocolHandler.sendTo(client, data);
    }

    public static void main(String[] args) {
        String module = "ServerNode: ";
        if (args.length == 0) {
            System.out
                .println("Usage: java cgl.narada.node.ServerNode portNum a/u" +
                    "[assigned|unassigned addr] transportType[niotcp/tcp/udp]");
            System.exit(0);
        }

        String portNum = args[0];
        try {
            Integer.parseInt(portNum);
        } catch (Exception e) {
            System.out.println(module + "Specified port number (" + portNum
                + ") is not a valid one!");
            System.exit(0);
        }
        boolean assignedAddress = false;
        if (args.length > 1) {
            if (args[1].equals("a"))
                assignedAddress = true;
        }

        String transportType = "niotcp";

        if (args.length > 2) {
            String transport = args[2];            
            if (transport.equals("tcp") || transport.equals("udp")) {
                transportType = transport;
             }
        }

        ServerNode serverNode = new ServerNode(assignedAddress);
        Properties props = new Properties();

        if (transportType.equals("niotcp")) {
            props.put("NIOTCPServerPort", portNum);
        } else if (transportType.equals("tcp")) {
            props.put("TCPServerPort", portNum);
        } else if (transportType.equals("udp")) {
            props.put("UDPListenerPort", portNum);
        }
        serverNode.setUpNode(props, transportType);

        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        String cmd;
        StringTokenizer tok;

        System.out
            .println("\n" + "Type h for help and Usage indicators" + "\n");

        while (true) {
            try {
                cmd = r.readLine();
                if (cmd.startsWith("h")) {
                    System.out
                        .println("Connect              -> c server portNum "
                            + "t[tcp]/u[udp]/m[multicast]/h[http]");
                    System.out
                        .println("Node Address Request -> na server:portNum "
                            + "levels");
                    System.out
                        .println("Create Gateway       -> ga server:portNum level");
                    System.out
                        .println("Replication          -> s storageFileName "
                            + "replicationGran");
                }

                if (cmd == null) {
                    break;
                }

                if (cmd.startsWith("c ")) {
                    tok = new StringTokenizer(cmd, " ");
                    if (tok.countTokens() != 4) {
                        System.out
                            .println("Usage -> c server portNum n/t/u/m/h");
                        continue;
                    }
                    tok.nextToken();
                    String host = tok.nextToken();
                    int port = Integer.parseInt(tok.nextToken());
                    String medium = tok.nextToken();
                    String transport = "niotcp";
                    if (medium.equals("t"))
                        transport = "tcp";
                    else if (medium.equals("u"))
                        transport = "udp";
                    else if (medium.equals("m"))
                        transport = "multicast";
                    else if (medium.equals("h"))
                        transport = "http";
                    else if (medium.equals("n"))
                        transport = "niotcp";
                    serverNode.connectTo(host, port, transport);
                }
                /** end processing of connect */

                if (cmd.startsWith("na")) {
                    tok = new StringTokenizer(cmd, " ");
                    if (tok.countTokens() != 3) {
                        System.out.println("Usage -> na server:portNum levels");
                        continue;
                    }
                    tok.nextToken();
                    String client = tok.nextToken();
                    int levels = Integer.parseInt(tok.nextToken());
                    serverNode.nodeAdditionRequest(client, levels);
                }
                /** end processing of node address request */

                if (cmd.startsWith("ga")) {
                    tok = new StringTokenizer(cmd, " ");
                    if (tok.countTokens() != 3) {
                        System.out.println("Usage -> ga server:portNum level");
                        continue;
                    }
                    tok.nextToken();
                    String client = tok.nextToken();
                    int level = Integer.parseInt(tok.nextToken());
                    serverNode.gatewayCreationRequest(client, level);
                }
                /** end processing of gateway creation request */

                if (cmd.startsWith("send")) {
                    tok = new StringTokenizer(cmd, " ");
                    tok.nextToken();
                    String client = tok.nextToken();
                    byte[] data = tok.nextToken().getBytes();
                    serverNode.sendTo(client, data);
                }

            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

}
